package com.barbarossa.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.barbarossa.activity.R;
import com.barbarossa.activity.data.VodDataManager;
import com.barbarossa.activity.widget.VodHistoryListAdapter;
import com.barbarossa.vod.datatype.TorrentFile;
import com.barbarossa.vod.datatype.TorrentFileLink;
import com.barbarossa.vod.datatype.VideoLink;
import com.barbarossa.vod.datatype.VodHistoryRecord;
import com.barbarossa.vod.utils.VodUtils;
import com.barbarossa.vod.utils.WebUtils;
import com.google.ads.AdView;

public class VodassistActivity extends SherlockActivity implements
		OnChildClickListener, OnGroupClickListener, OnNavigationListener {

	final int MENUITEM_OPENLINK = 1;
	final int MENUITEM_OPENFILE = 2;
	final int MENUITEM_HELP = 3;
	final int MENUITEM_CLEARHISTORY = 4;

	final public static String ACTION_OPENLINK = "com.barbarossa.activity.VodassistActivity.ACTION_OPENLINK";
	final public static String ACTION_OPENFILE = "com.barbarossa.activity.VodassistActivity.ACTION_OPENFILE";

	final int VALID_RECORD_TORRENT = 1;
	final int VALID_RECORD_LINK = 2;
	final int INVALID_RECORD_UNKNOWN = -1;
	final int INVALID_LINK_WRONGLINK = -2;
	final int INVALID_LINK_NOTREADY = -3;
	final int INVALID_TORRENT_UNABLETOPARSE = -4;
	final int INVALID_TORRENT_WRONGTORRENT = -5;
	final int INVALID_TORRENT_NOFILE = -6;
	final int INVALID_TORRENTFILE_WRONGLINK = -7;
	final int INVALID_TORRENTFILE_NOTREADY = -8;

	final int MESSAGE_OPENURI_SUCCEEDED = 1;
	final int MESSAGE_OPENURI_FAILED = 2;
	final int MESSAGE_DOWNLOADM3U8_SUCCEEDED = 3;
	final int MESSAGE_DOWNLOADM3U8_FAILED = 4;

	final String DATA_PATH = "pirate-radio";
	final String DATA_TEMP_PATH = DATA_PATH + "/temp";
	protected String mPath = null;
	protected String mTempPath = null;

	protected ExpandableListView elv = null;
	protected VodHistoryListAdapter elvAdapter = null;

	protected VodUtils vu = new VodUtils();
	protected AQuery aq = null;
	protected boolean openAsLink = true;
	
	private AdView adView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		aq = new AQuery(this);

		File fExternalDirectory = Environment.getExternalStorageDirectory();
		mPath = fExternalDirectory.getAbsolutePath() + "/" + DATA_PATH;
		mTempPath = fExternalDirectory.getAbsolutePath() + "/" + DATA_TEMP_PATH;

		createPath(mPath);
		createPath(mTempPath);
		VodDataManager.getInstance(mPath);

		elv = aq.id(R.id.expandableListViewMain).getExpandableListView();
		elv.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
		elv.setOnGroupClickListener(this);
		elv.setOnChildClickListener(this);

		loadData();

		Context context = getSupportActionBar().getThemedContext();
		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
				context, R.array.opentype, R.layout.sherlock_spinner_item);
		list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		getSupportActionBar().setListNavigationCallbacks(list, this);

		if (ACTION_OPENLINK.equals(getIntent().getAction()))
			openUri(getIntent().getDataString(), true);
		else if (ACTION_OPENFILE.equals(getIntent().getAction()))
			openUri(getIntent().getDataString(), false);

		// ((VodHistoryListAdapter)elv.getAdapter()).notifyDataSetChanged();
		// Toast.makeText(this, "clickable="+elv.isClickable(),
		// Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (RESULT_OK != resultCode)
			return;

		switch (requestCode) {
		case MENUITEM_OPENLINK:
			openUri(data.getDataString(), true);
			break;
		case MENUITEM_OPENFILE:
			openUri(data.getDataString(), false);
			break;
		}
	}

	protected void openUri(String uri, boolean asLink) {
		/*
		 * VodHistoryRecord rec; if (asLink) rec =
		 * vu.getVodHistoryRecordFromLink(uri); else rec =
		 * vu.getVodHistoryRecordFromTorrent(uri); if (null != rec) {
		 * ExpandableListView elv = aq.id(R.id.expandableListViewMain)
		 * .getExpandableListView(); VodHistoryListAdapter elvAdapter =
		 * (VodHistoryListAdapter) elv .getExpandableListAdapter();
		 * elvAdapter.addHistoryRecord(rec);
		 * VodDataManager.getInstance(null).addVodHistoryRecord(rec); }
		 */
		new OpenUriThread(uri, asLink).start();
	}

	protected void loadData() {
		if (null == elvAdapter) {
			elvAdapter = new VodHistoryListAdapter(this);
			elv.setAdapter(elvAdapter);
		}

		ArrayList<VodHistoryRecord> vodHistory = VodDataManager.getInstance(
				null).getVodHistoryRecords();
		elvAdapter.setVodHistory(vodHistory);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Used to put dark icons on light action bar
		// ActionBarSherlock abs = getSherlock();

		MenuItem openLink = menu.add(Menu.NONE, MENUITEM_OPENLINK, Menu.FIRST,
				R.string.menu_open_link);
		openLink.setIcon(R.drawable.ab_5_content_new_attachment);
		openLink.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		MenuItem openFile = menu.add(Menu.NONE, MENUITEM_OPENFILE,
				Menu.FIRST + 1, R.string.menu_open_file);
		openFile.setIcon(R.drawable.ab_5_content_new_event);
		openFile.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		MenuItem clearHistory = menu.add(Menu.NONE, MENUITEM_CLEARHISTORY,
				Menu.FIRST + 2, R.string.menu_clear_history);
		clearHistory.setIcon(R.drawable.ic_action_delete);
		clearHistory.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		MenuItem help = menu.add(Menu.NONE, MENUITEM_HELP, Menu.FIRST + 3,
				R.string.menu_help);
		help.setIcon(R.drawable.ab_2_action_help);
		help.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (item.getItemId()) {
		case MENUITEM_OPENFILE:
			intent = new Intent(this, TorrentFileChooserActivity.class);
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, MENUITEM_OPENFILE);
			break;
		case MENUITEM_OPENLINK:
			intent = new Intent(this, OpenLinkActivity.class);
			startActivityForResult(intent, MENUITEM_OPENLINK);
			break;
		case MENUITEM_CLEARHISTORY:
			if (elvAdapter.getGroupCount() > 0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.content_clear_history)
						.setPositiveButton(R.string.prompt_ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										elvAdapter.clearHistoryRecord();
										VodDataManager.getInstance(null)
												.clearAll();
										clearTempPath();
									}
								})
						.setNegativeButton(R.string.prompt_cancel,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
			break;
		case MENUITEM_HELP:
			intent = new Intent(this, HelpActivity.class);
			startActivity(intent);
			break;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	protected void openM3U8File(File f) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(f);
		intent.setDataAndType(uri, "video/*");
		startActivity(intent);

	}

	protected File downloadM3U8(String url) {
		WebUtils wu = new WebUtils();
		try {
			File fRet = File.createTempFile("temp", ".m3u8",
					new File(mTempPath));
			if (wu.getDownloadedFile(url, fRet, null))
				return fRet;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	protected void playM3U8Link(String url) {
		if (openAsLink) {
			Intent it = new Intent(Intent.ACTION_VIEW);
			Uri uri = Uri.parse(url);
			// use mime-type:application/x-mpegURL or vnd.apple.mpegURL
			it.setDataAndType(uri, "application/x-mpegURL");
			// it.setDataAndType(uri, "vnd.apple.mpegURL");
			startActivity(it);
			return;
		}

		DownloadM3U8Thread thread = new DownloadM3U8Thread(url);
		thread.start();
		return;

	}

	protected void playRecord(VideoLink link) {

		final String m3u8Links[] = link.getM3u8Link();

		if (m3u8Links.length <= 1) {
			playM3U8Link(m3u8Links[0]);
			return;
		}

		final CharSequence[] items_full = { getText(R.string.resolution_sd),
				getText(R.string.resolution_hd),
				getText(R.string.resolution_uhd) };
		CharSequence items[] = new CharSequence[m3u8Links.length];
		System.arraycopy(items_full, 0, items, 0, items.length);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.title_resolution);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				playM3U8Link(m3u8Links[item]);
				return;
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	protected int checkVodHistoryRecord(VodHistoryRecord record) {
		// VALID_RECORD_TORRENT
		// VALID_RECORD_LINK
		VideoLink link = record.getLinkRecord();
		TorrentFile torrent = record.getTorrentRecord();

		if (null != link) {
			if (null == link.getM3u8Link())
				return INVALID_LINK_WRONGLINK;
			if (0 == link.getM3u8Link().length)
				return INVALID_LINK_NOTREADY;
			return VALID_RECORD_LINK;
		}

		if (null != torrent) {
			if (null == torrent.getInfoHash())
				return INVALID_TORRENT_UNABLETOPARSE;
			TorrentFileLink tflinks[] = torrent.getLinks();
			if (null == tflinks)
				return INVALID_TORRENT_WRONGTORRENT;
			if (0 == tflinks.length)
				return INVALID_TORRENT_NOFILE;
			for (int i = 0; i < tflinks.length; i++) {
				link = tflinks[i];
				if (null == link.getM3u8Link())
					return INVALID_TORRENTFILE_WRONGLINK;
				if (0 == link.getM3u8Link().length)
					return INVALID_TORRENTFILE_NOTREADY;
			}
			return VALID_RECORD_TORRENT;
		}

		return INVALID_RECORD_UNKNOWN;
	}

	protected void processInvalidRecord(VodHistoryRecord record,
			int groupPosition, int checkResult) {
		// TODO:
		Toast.makeText(this, "wrong record, reason=" + checkResult,
				Toast.LENGTH_SHORT).show();
	}

	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {

		ArrayList<VodHistoryRecord> history = elvAdapter.getVodHistory();
		VodHistoryRecord record = history.get(groupPosition);
		int checkResult = checkVodHistoryRecord(record);
		if (checkResult < 0) { // invalid record
			processInvalidRecord(record, groupPosition, checkResult);
			return true;
		}

		if (VALID_RECORD_LINK == checkResult) {
			playRecord(record.getLinkRecord());
			return true;
		}

		return false;
	}

	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		// TODO Auto-generated method stub
		ArrayList<VodHistoryRecord> history = elvAdapter.getVodHistory();
		TorrentFile torrent = history.get(groupPosition).getTorrentRecord();
		TorrentFileLink torrentLink = torrent.getLinks()[childPosition];

		playRecord(torrentLink);
		return true;
	}

	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		// return true;
		if (0 == itemPosition)
			openAsLink = true;
		else
			openAsLink = false;
		return true;
	}

	protected void createPath(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
	}

	protected void clearTempPath() {
		File fTemp = new File(mTempPath);
		File[] files = fTemp.listFiles();
		for (File f : files) {
			f.delete();
		}
	}

	private class OpenUriThread extends Thread {
		String mUri;
		boolean mAsLink;

		public OpenUriThread(String uri, boolean asLink) {
			super();
			// TODO Auto-generated constructor stub
			mUri = uri;
			mAsLink = asLink;
		}

		@Override
		public void run() {
			VodHistoryRecord rec;
			if (mAsLink)
				rec = vu.getVodHistoryRecordFromLink(mUri);
			else
				rec = vu.getVodHistoryRecordFromTorrent(mUri);
			if (null != rec)
				mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_OPENURI_SUCCEEDED, 0, 0, rec));
			else
				mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_OPENURI_FAILED));
		}

	}

	private class DownloadM3U8Thread extends Thread {
		String mUrl;

		public DownloadM3U8Thread(String url) {
			super();
			// TODO Auto-generated constructor stub
			mUrl = url;
		}

		@Override
		public void run() {
			File fM3U8 = downloadM3U8(mUrl);
			if (null == fM3U8) {
				mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DOWNLOADM3U8_FAILED));				
				return;
			}

			Uri uri = Uri.fromFile(fM3U8);
			mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DOWNLOADM3U8_SUCCEEDED, 0, 0, uri));
		}

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MESSAGE_OPENURI_SUCCEEDED:
				VodHistoryRecord rec = (VodHistoryRecord)msg.obj;
				elvAdapter.addHistoryRecord(rec);
				VodDataManager.getInstance(null).addVodHistoryRecord(rec);
				break;
			case MESSAGE_OPENURI_FAILED:
				break;
			case MESSAGE_DOWNLOADM3U8_SUCCEEDED:
				Intent it = new Intent(Intent.ACTION_VIEW);
				Uri uri = (Uri) msg.obj;
				it.setDataAndType(uri, "video/*");
				startActivity(it);
				break;
			case MESSAGE_DOWNLOADM3U8_FAILED:
				Toast.makeText(VodassistActivity.this, "download error, todo", Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};
}